package com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo09;

import com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton;

import java.io.*;

/**
 * @PROJECT_NAME design_patterns
 * @DESCRIPTION 测试类
 * @AUTHOR CNBruceLee
 * @DATE 2021/7/8 20:15
 */
public class Test {

    //通过序列化破话单例模式（改进前）
    @org.junit.Test
    public void test1() throws Exception {
        //1、实例化对象
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton singleton1 = Singleton.getInstance();

        //2、向文件中写对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\30260\\Desktop\\a.txt"));
        oos.writeObject(singleton1);
        oos.close();//释放资源

        //3、从文件中获取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\30260\\Desktop\\a.txt"));
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo07.Singleton singleton2 = (Singleton) ois.readObject();
        ois.close();//释放资源

        //通过序列化之后，在获取的对象是不同的了，也就是不在是一个对象，而是两个，进而破坏了单例模式
        System.out.println(singleton1 == singleton2);//-->false
        System.out.println(singleton1);
        System.out.println(singleton2);
    }

    //通过序列化破话单例模式（改进后）
    @org.junit.Test
    public void test2() throws Exception {
//1、实例化对象
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo09.Singleton singleton1 =
                com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo09.Singleton.getInstance();

        //2、向文件中写对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\30260\\Desktop\\a.txt"));
        oos.writeObject(singleton1);
        oos.close();//释放资源

        //3、从文件中获取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\30260\\Desktop\\a.txt"));
        com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo09.Singleton singleton2 =
                (com.bruce.demo2.patterns.demo1.creational.demo01.singleton.demo09.Singleton) ois.readObject();
        ois.close();//释放资源

        //通过序列化之后，在获取的对象是不同的了，也就是不在是一个对象，而是两个，进而破坏了单例模式
        System.out.println(singleton1 == singleton2);//-->true
        System.out.println(singleton1);
        System.out.println(singleton2);
    }
}
